//
//  Album.m
//  UI06_UIScrollView_相册
//
//  Created by Scott on 16/3/16.
//  Copyright © 2016年 Scott. All rights reserved.
//

#import "Album.h"
#import "MyScrollView.h"

@interface Album () <UIScrollViewDelegate>

// 两个子控件
@property (nonatomic, retain) UIPageControl *page;
@property (nonatomic, retain) MyScrollView *scroll;

@end

@implementation Album

- (void)dealloc {
    
    [_page release];
    [_scroll release];
    [super dealloc];
}

#pragma mark - Creating and Init
- (instancetype)initWithFrame:(CGRect)frame withImages:(NSArray<UIImage *> *)images {
    
    self = [super initWithFrame:frame];
    if (self) {
    
        [self configWithFrame:frame images:images];
    }
    return self;
}

#pragma mark - config
- (void)configWithFrame:(CGRect)frame images:(NSArray *)images {
    
    // 创建scoll对象, 注意frame参数远点不是{0, 0}, 可用bounds属性代替
    self.scroll = [[MyScrollView alloc] initWithFrame:self.bounds withImages:images delegate:self];
    
    [self addSubview:self.scroll];
    [_scroll release];
    
    // 指定代理人
    self.scroll.delegate = self;
    
    
    // 设置缩放比例(最大, 最小)
//    self.scroll.minimumZoomScale = 0.5;
//    self.scroll.maximumZoomScale = 2;
    
    // 创建pageControll对象
    self.page = [[UIPageControl alloc] initWithFrame:CGRectMake(0, frame.size.height - 40, frame.size.width, 40)];
    [self addSubview:self.page];
    [_page release];
    
    // 页数.
    self.page.numberOfPages = images.count;
    
    // 添加事件
    [self.page addTarget:self action:@selector(handlePage:) forControlEvents:UIControlEventValueChanged];
    
    
    
}

- (void)handlePage:(UIPageControl *)page {
    
    // scroll滚动(contentOffset)
    [self.scroll setContentOffset:CGPointMake(self.bounds.size.width * page.currentPage, 0) animated:YES];
    
}

#pragma mark - ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
//    NSLog(@"%s", __FUNCTION__);
    
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    
//    NSLog(@"%s", __FUNCTION__);
    
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView {
    
//    NSLog(@"%s", __FUNCTION__);
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    // page跟随scoll滚动而改变
    self.page.currentPage = scrollView.contentOffset.x / self.bounds.size.width;
    
    // 判断滑动的scrollView是大ScrollView时
    if (scrollView == self.scroll) {

        for (UIScrollView *scrollOfSmall in self.scroll.subviews) {
            
            if ([scrollOfSmall.class isSubclassOfClass:[UIScrollView class]]) {
                
                scrollOfSmall.zoomScale = 1;
            }
            
        }
    }
    
}

/** 返回需要缩放的视图. */
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    
    // 判断是小scrollView
    if (scrollView != self.scroll) {
        
        NSLog(@"%@", scrollView);
        return [scrollView.subviews firstObject];
    
    } else {
        
        return nil;
    }

}


@end
